package com.xie.o2o.service.impl;

import com.xie.o2o.dao.LocalAuthDao;
import com.xie.o2o.dto.LocalAuthExecution;
import com.xie.o2o.entity.LocalAuth;
import com.xie.o2o.enums.LocalAuthStateEnum;
import com.xie.o2o.service.LocalAuthService;
import com.xie.o2o.util.MD5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @create: xie
 */
@Service
public class LocalAuthServiceImpl implements LocalAuthService {
    @Autowired
    private LocalAuthDao localAuthDao;

    @Override
    public LocalAuth getLocalAuthByUsernameAndPwd(String username, String password) {
        return localAuthDao.queryLocalByUserNameAndPwd(username, MD5.getMd5(password));
    }

    @Override
    public LocalAuth getLocalAuthByUserId(long userId) {
        return localAuthDao.queryLocalByUserId(userId);
    }

    /**
     * 绑定平台账号
     *
     * @param localAuth
     * @return
     * @throws RuntimeException
     */
    @Override
    @Transactional
    public LocalAuthExecution bindLocalAuth(LocalAuth localAuth) throws RuntimeException {
        //控制判断，username、password、userid不能为空
        if (localAuth == null || localAuth.getPassword() == null || localAuth.getUsername() == null || localAuth.getPersonInfo() == null
                || localAuth.getPersonInfo().getUserId() == null) {
            return new LocalAuthExecution(LocalAuthStateEnum.NULL_AUTH_INFO);
        }
        //查询用户是否已绑定平台账号
        LocalAuth localAuth1 = localAuthDao.queryLocalByUserId(localAuth.getPersonInfo().getUserId());
        if (localAuth1 != null) {
            //已绑定则直接退出，保证平台账号唯一性
            return new LocalAuthExecution(LocalAuthStateEnum.ONLY_ONE_ACCOUNT);
        }
        //如果没绑定，则创建一个平台账号与该用户绑定
        localAuth.setCreateTime(new Date());
        localAuth.setLastEditTime(new Date());
        //对密码MD5加密
        localAuth.setPassword(MD5.getMd5(localAuth.getPassword()));
        localAuthDao.insertLocalAuth(localAuth);
        return new LocalAuthExecution(LocalAuthStateEnum.SUCCESS, localAuth);
    }

    @Override
    @Transactional
    public LocalAuthExecution modifyLocalAuth(Long userId, String username, String password, String newPassword) throws RuntimeException {
        //非空判断，判断传入的用户id，新旧密码是否为空，是否相同，不满足条件则返回错误信息
        if (userId != null && username != null && password != null && newPassword != null && !password.equals(newPassword)) {
            localAuthDao.updateLocalAuth(userId, username, MD5.getMd5(password), MD5.getMd5(newPassword), new Date());
            return new LocalAuthExecution(LocalAuthStateEnum.SUCCESS);
        } else {
            return new LocalAuthExecution(LocalAuthStateEnum.NULL_AUTH_INFO);
        }
    }
}
